<!--打卡 -->
<template>
  <div class="page clockIn-page" data-page="clockIn" style="z-index: 2;">
      <div class="link-page-nav">
          <a href="#" class="link"  @click="$root.backToTab()">
              <i class="iconfont icon-zuo"></i>
          </a>
      </div>
      <div class="link-page-top" style="padding-bottom: 17px;">
          <div class="link-page-list-title">打卡</div>
      </div>
      <div class="go-history-list">
      	<a href="/clockInRule/" class="link" style="color: #000000;margin-right: 10px;">
            <i class="iconfont icon-APPicon_lishi2" style="font-size: 23px;"></i>
        </a>
        <a href="/clockInRecords/" class="link" style="color: #000000;margin-right: 10px;">
            <i class="iconfont icon-APPicon_lishi" style="font-size: 23px;"></i>
        </a>
     </div>
	<div class="page-content infinite-scroll-content" id="clockInCentent_{{getNewId}}" style="padding-bottom: 150px;">
		<div id="clockInBody_{{getNewId}}" style="display:none">
			<div class="clockIn-page-top">
					<div class="fireHazardList-list-item">
							<dev class="highDager_detail">
								<div id="cockInMap_{{getNewId}}" class="highDanger-item-border">
								</div>
								<div>
									<span id="clockInDistance_{{getNewId}}"></span>
									<span class="baiduMapRefresh" @click="getNearestOrgByLocation"><i class="iconfont icon-shuaxin"></i>刷新</span>
								</div>
	
								<div class="highDanger-item-unit-desc">
									<i class="iconfont icon-APPicon_dingwei"
										style="color: #2471CA; margin-left:-8px;margin-right: 4px;font-size: 15px;"></i><span
										class="highDanger-item-unit" id="clockAddr_{{getNewId}}"></span>
								</div>
							</dev>
					</div>
			</div>
			<div class="detailpPlan">
				<dev id="organizationName_in_{{getNewId}}" class="clockIn-organizationName-title"></dev>
	            <div class="clockInPlan">
	            	<div class="clockInBtn" id="clockInBtn_{{getNewId}}" @click="getCurrentClock">
	            		<p id="clockInBtnTip_{{getNewId}}" class="clockBtnTip">上班打卡</p>
	            		<p id="clockInShowTime_{{getNewId}}"></p>
	            	</div>
	            </div>
		        <div style="text-align: center;">
		            <div class="inspection-time-title" style="color: #2471CA;margin-bottom: 10px;">一  值班时间  一</div>
					<span id="dutyTime_{{getNewId}}"></span>
		        </div>
		   </div>
	   </div>
	</div>
</div>
  </div>
</template>
<script>
    return {
        data: function() {
            return {
                pageName: "clockIn",
                cockInType: 0,
                lon: 0, //用户当前位置经度
                lat: 0, //用户当前位置纬度
                _distance: 0, //人员距离联网单位的距离(离开打卡位置的距离)
                networkingUnitLon: 0, //联网单位经度
                networkingUnitLat: 0, //联网单位纬度
                networkingUnitDistance: 0, //联网单位打卡范围半径
                currentOndutyResult: 0, //当前上班打卡状态
                currentOffdutyResult: 0, //当前下班打卡状态
                currentWatchStartTime: "",
                currentWatchEndTime: "",
                getNewId: (new Date()).getTime(),
            }
        },
        methods: {
            backToRefresh:function(){
                var slef = this;
                // self.getNativeBackLocation();
            },
            goToHistory: function() {
                app.router.navigate("/keyIssuesHistoryList/");
            },
            baiduMap: function() {
                var self = this;
                // 百度地图API功能
                var map = new BMap.Map("cockInMap_"+self.getNewId); // 创建Map实例
                var point = new BMap.Point(self.lon, self.lat); //用户当前位置经纬度 先写死
                var pointCircle = new BMap.Point(self.networkingUnitLon, self.networkingUnitLat); //原点经纬度(最近联网单位)  
                //var circle = new AMap.Circle({
                //    center: new AMap.LngLat("116.403322", "39.920255"),// 圆心位置
                //    radius: 1000, //半径
                //        strokeColor: "#FF33FF", //线颜色
                //        strokeOpacity: 0.2, //线透明度
                //        strokeWeight: 3,    //线宽
                //        fillColor: "#1791fc", //填充色
                //        fillOpacity: 0.05//填充透明度
                //创建圆
                var circle = new BMap.Circle(pointCircle, self.networkingUnitDistance, {
                    strokeColor: "blue",
                    fillColor: "blue",
                    strokeWeight: 1,
                    fillOpacity: 0.2,
                    strokeOpacity: 0.2
                });
                var marker = new BMap.Circle(pointCircle, 20, {
                    strokeColor: "blue",
                    strokeWeight: 2
                }); //创建圆心点位置
                //创建用户头像标注
                var myIcon1 = new BMap.Icon(picPeopleNo(userInfor.headUrl), new BMap.Size(50, 50), {
                    imageSize: new BMap.Size(17, 17), // 引用图片实际大小
                    anchor: new BMap.Size(35, 55),
                    imageOffset: new BMap.Size(5, 4) // 图片相对视窗的偏移
                });
                var myIcon = new BMap.Icon('/ilink-app-h5-zd/static/img/rdspFile_1552981560146.png', new BMap.Size(35, 55), {
                    anchor: new BMap.Size(35, 55)
                });
                var myIconMarker = new BMap.Marker(point, {
                    icon: myIcon
                }); // 创建标注
                var userIconMarker = new BMap.Marker(point, {
                    icon: myIcon1
                }); // 创建标注
                map.centerAndZoom(point, 15); // 初始化地图,设置中心点坐标和地图级别
                //添加覆盖物
                map.addOverlay(circle); //增加圆
                map.addOverlay(marker); //增加圆
                map.addOverlay(myIconMarker); //将将标注添加到地图中
                map.addOverlay(userIconMarker); //将用户头像标注
                //添加地图类型控件
                //map.addControl(new BMap.MapTypeControl({
                //mapTypes:[
                //BMAP_NORMAL_MAP,
                //BMAP_HYBRID_MAP
                // ]}));      
                //map.setCurrentCity("深圳");          // 设置地图显示的城市 此项是必须设置的
                map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

                //坐标转换为地址
                var gc = new BMap.Geocoder();
                gc.getLocation(point, function(rs) {
                    var addComp = rs.addressComponents;
                    var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                    $("#clockAddr_"+self.getNewId).html("位置：" + address);
                });

                self._distance = (map.getDistance(point, pointCircle)).toFixed(2); //人员距离打卡位置的距离
                if (isNaN(self._distance)) {
                    self._distance = 99999999999999;
                }
                self._distance = parseFloat(self._distance);
                //获取不到单位的坐标或者距离太远
                if (self._distance > self.networkingUnitDistance) { //不在打卡范围内
                	$("#clockInDistance_"+self.getNewId).removeClass("normal-highDanger-item-desc");
                	$("#clockInDistance_"+self.getNewId).html("您当前不在打卡范围内").addClass("abnormal-highDanger-item-desc");
                } else { //在打卡范围内
                	$("#clockInDistance_"+self.getNewId).removeClass("abnormal-highDanger-item-desc");
                	$("#clockInDistance_"+self.getNewId).html("您当前已在打卡范围内").addClass("normal-highDanger-item-desc");
                }
                self.getUserCurrentWatchDetail();
            },
            //根据当前时间判断当前打卡权限
            //clockType 打卡类型，1：上班卡，2：下班卡
            getCurrentClock: function() {
                let self = this;
                let now = moment().format("YYYY-MM-DD HH:mm:ss");
                
                if (self._distance > self.networkingUnitDistance) { //不在打卡范围内
                	$("#clockInDistance_"+self.getNewId).removeClass("normal-highDanger-item-desc");
                	$("#clockInDistance_"+self.getNewId).html("您当前不在打卡范围内").addClass("abnormal-highDanger-item-desc");
                    app.dialog.alert('<span style="color:red">您不在打卡范围之内<span>', '');
                	return;
                } 
                
                //下班卡
                if (self.currentOndutyResult != 0) {
                    //下班未打卡状态
                    if (self.currentOffdutyResult == 0) {
                        self.cockInType = 2;
                        //在下班时间之前
                        if (moment(now).isBefore(self.currentWatchEndTime)) {
                            app.dialog.confirm('<span style="color:red">你早退了<span>', '',
                                function() {
                                    self.clockInAndOut();
                                },
                                function() {});
                        } else {
                            self.clockInAndOut();
                        }
                    }
                    //今日打卡已经结束
                    else {
                        app.dialog.alert('<span style="color:red">今日打卡已经结束<span>', '');
                    }
                }
                //下班卡
                else {
                    if(self.currentOffdutyResult != 0){
                       //今日打卡已经结束
                       app.dialog.alert('<span style="color:red">今日打卡已经结束<span>', '');
                    }else{
	                	self.cockInType = 1;
	                    //当前时间在上班时间之后
	                    if (moment(now).isAfter(self.currentWatchEndTime)) {
	                    	var sysTime = new Date();
	                    	var d1 = new Date(self.currentWatchEndTime.replace(/-/g,"/"));
	                    	if(parseInt(sysTime - d1)/1000<14400){
	                    		//超过下班时间在4小时之内，用户只能打下卡
	                    		self.cockInType = 2;
	                        	self.clockInAndOut();
	                    	}else{
	                        	//超过下班时间4小时之后，用户不能再打上班时间卡
	                        	app.dialog.alert('<span style="color:red">下班时间已过,不能打卡<span>', '');
	                    	}
	                    }else if(moment(now).isAfter(self.currentWatchStartTime)){
	                    	app.dialog.confirm('<span style="color:red">你迟到了<span>', '',
	                                function() {
	                                    self.clockInAndOut();
	                                },
	                                function() {});
	                    }
	                    else {
	                        self.clockInAndOut();
	                    }
	                }
                }
            },
            //打卡
            clockInAndOut: function() {
                var self = this;
                if (1 <= self.cockInType) {
                    let json = {
                        "lon": self.lon,
                        "lat": self.lat
                    };
                    let ondutyLonlat = "";
                    let offdutyLonlat = "";
                    if (self.cockInType == 1) {
                        ondutyLonlat = JSON.stringify(json);
                        offdutyLonlat = "";
                    } else {
                        offdutyLonlat = JSON.stringify(json);
                        ondutyLonlat = "";
                    }
                    Dao.clockInAndOut({
                        userName: userInfor.accountName,
                        clockType: self.cockInType,
                        ondutyLonlat: ondutyLonlat, //上班打卡经纬度
                        offdutyLonlat: offdutyLonlat, //下班打卡经纬度
                    }, function(total,info, status) {
                        if (status == 200) {
                            app.methods.showToastCenter("打卡成功");
                            self.getUserCurrentWatchDetail();
                        } else {
                            app.methods.showToastCenter(info);
                        }
                    }, true);
                } else {
                    app.methods.showToastCenter("您不在打卡范围之内");
                }
            },
            //获取用户当前打卡信息
            getUserCurrentWatchDetail: function() {
                var self = this;
                Dao.getUserCurrentWatchDetail({
                    userName: userInfor.accountName,
                }, function(data) {
                	var range = self.networkingUnitDistance;
                    if (data) {
                        if (data.watchStartTime != null && data.watchEndTime != null) {
                            $("#dutyTime_"+self.getNewId).html(data.watchStartTime + "~" + data.watchEndTime);
                        }
                        var ondutyResult = data.ondutyResult; //上班打卡结果  0:未打卡 1:打卡 2:迟到 3:早退
                        var offdutyResult = data.offdutyResult; //下班打卡结果 0:未打卡 1:打卡 2:迟到 3:早退

                        self.currentWatchStartTime = data.watchStartTime; //上班时间
                        self.currentWatchEndTime = data.watchEndTime; //下班时间

                        self.currentOndutyResult = ondutyResult;
                        self.currentOffdutyResult = offdutyResult;

                        //上班未打卡
                        if (ondutyResult == 0) {
                        	let now = moment().format("YYYY-MM-DD HH:mm:ss");
                        	var sysTime = new Date();
                        	var d1 = new Date(self.currentWatchEndTime.replace(/-/g,"/"));
                        	//上班未打卡,下班已打卡后不能在打卡
                        	if(offdutyResult != 0){
                        		if (offdutyResult == 3) {
                                    $("#clockInBtnTip_"+self.getNewId).html("下班早退");
                                    $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn2");
                                }else if (offdutyResult == 1) {
                                    $("#clockInBtnTip_"+self.getNewId).html("下班正常");
                                    $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn5");
                                }
                        	}else if(moment(now).isAfter(self.currentWatchEndTime) && parseInt(sysTime - d1)/1000<14400){
                           		//超过下班时间在4小时之内，用户只能打下卡
                           		$("#clockInBtnTip_"+self.getNewId).html("下班打卡");
	                            if (self._distance > range) {
	                                //不在打卡范围内
	                                $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn3");
	                            } else {
	                                //在打卡范围内
	                                self.cockInType = 2;
	                                $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn");
	                            }
                            }else{
	                        	$("#clockInBtnTip_"+self.getNewId).html("上班打卡");
	                            if (self._distance > range) {
	                                //不在打卡范围内
	                                $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn3");
	                            } else {
	                                //在打卡范围内
	                                self.cockInType = 1;
	                                $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn");
	                            }
                            }
                        } else {
                            //早退
                            if (offdutyResult == 3) {
                                $("#clockInBtnTip_"+self.getNewId).html("下班早退");
                                $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn2");
                            }else if (offdutyResult == 1) {
                                $("#clockInBtnTip").html("下班正常");
                                $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn5");
                            } else {
                                //已经打了上班卡
                                $("#clockInBtnTip_"+self.getNewId).html("下班打卡");
                                if (self._distance > range) {
                                    //不在打卡范围内
                                    $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn3");
                                } else {
                                    //在打卡范围内
                                    self.cockInType = 2;
                                    $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn");
                                }
                            }
                        }
                    } else {
                        //查询不到记录沒有打卡权限
                        if (self._distance > range) {
                            //不在打卡范围内
                            $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn3");
                        } else {
                            //在打卡范围内
                            self.cockInType = 1;
                            $("#clockInBtn_"+self.getNewId).attr('class', '').addClass("clockInBtn");
                        }
                    }
                }, true);
            },
            timeCurrent: function() { //显示时间
                var self = this;
                var d = new Date();
                var time = '';
                time += d.getHours() > 9 ? d.getHours() + ':' : "0" + d.getHours() + ':';
                time += d.getMinutes() > 9 ? d.getMinutes() + ':' : "0" + d.getMinutes() + ':';
                time += d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds();
                $("#clockInShowTime_"+self.getNewId).html(time);
            },
            //根据坐标获取用户最近联网单位信息
            getNearestOrgByLocation: function() {
                var self = this;
                Dao.getFullInfoExt({
					orgId : userInfor.organizationIds,
				}, function(data) {
					if (data) {
                        self.networkingUnitLon = data.longitude; //经度
                        self.networkingUnitLat = data.latitude; //纬度
                        $("#organizationName_in_"+self.getNewId).html(data.name); //联网单位全称
                        self.networkingUnitDistance = parseFloat(data.radius); // 联网单位 范围打卡的半径
                    }
                    self.baiduMap(); //渲染地图
                }, true);
            },
            //获取原生回调的位置信息
            getNativeBackLocation: function(longitude, latitude, location) {
                var self = this;
                self.lon = longitude;
                self.lat = latitude;
                self.baiduMap();
            },
            isRest: function() {
            	var self = this;
                Dao.getUserCurrentWatchDetail({
                    userName: userInfor.accountName,
                }, function(data) {
                    if (data) {
                    	if (data.watchStartTime != null && data.watchEndTime != null) {
                        	var sysTime = new Date();
                        	var d1 = new Date(data.watchStartTime.replace(/-/g,"/"));
                        	var d2 = new Date(data.watchEndTime.replace(/-/g,"/"));
                        	//值班时间已过了 或者 值班时间大于当前系统时间 并且大于当前系统时间4个小时 (修改状态)
                        	if(parseInt(d2 - sysTime)/1000>-14400 || parseInt(d2 - sysTime)/1000<14400){
                        		$("#clockInBody_"+self.getNewId).show();
                            	//获取当前定位
                                native.requestLocation();
                                self.getNearestOrgByLocation(); //获取用户最近联网单位
                                self.timer&&clearInterval(self.timer)
                                self.timer=setInterval(self.timeCurrent, 1000);
                        	}else if(parseInt(d1 - sysTime)/1000>-14400){
                        		$("#clockInBody_"+self.getNewId).show();
                            	//获取当前定位
                                native.requestLocation();
                                self.getNearestOrgByLocation(); //获取用户最近联网单位
                                self.timer&&clearInterval(self.timer)
                                self.timer=setInterval(self.timeCurrent, 1000);
                        	}else{
                        		self.showRestPic()
                        	}
                        }else{
                            self.showRestPic()
                        }
                        
                    } else {
                        self.showRestPic()
                    }
                }, true);
            },
            showRestPic(){
                $("#clockInCentent_"+this.getNewId).html('<div style="text-align: center;">'
                    +'<div class="rest-txt text-center">当前无值班，好好休息</div>'
                    +'<img src="./img/punch/restbg1.png"></div>');
            }
        },
        on: {
            pageAfterIn: function(e, page) {
                var self = this;
                self.isRest();
            },
            pageBeforeOut: function (e, page) {
                clearInterval(this.timer)
            }
        }
    }
</script>
<style>
.clockIn-page .rest-txt{
    margin: 30% 0 40px;
    font-size: 20px;
    font-weight: 500;
    color: #2471ca;
}
</style>